<template>
  <div class="video-converter">
    <div class="upload-section">
      <div class="upload-box" @click="triggerFileInput">
        <input
            type="file"
            ref="fileInput"
            @change="handleFileSelect"
            accept="video/*"
            class="file-input"
            hidden
        >
        <div class="upload-hint" v-if="!selectedFile">
          <i class="upload-icon">📁</i>
          <p>点击或拖拽视频文件到此处</p>
        </div>
      </div>

      <div class="video-preview" v-if="videoPreview">
        <video
            ref="videoPlayer"
            :src="videoPreview"
            controls
            @loadedmetadata="handleVideoLoad"
            @timeupdate="handleTimeUpdate"
        ></video>

        <!-- 时间范围选择器 -->
        <div class="time-range-selector">
          <div class="time-slider">
            <div class="slider-container">
              <TimeRangeSlider
                  v-model="timeRange"
                  :min="0"
                  :max="videoDuration"
                  :step="0.1"
                  @update:modelValue="handleRangeChange"
              ></TimeRangeSlider>
            </div>
            <div class="time-labels">
              <span>开始: {{ formatTime(timeRange[0]) }}</span>
              <span>结束: {{ formatTime(timeRange[1]) }}</span>
              <span>时长: {{ formatTime(timeRange[1] - timeRange[0]) }}</span>
            </div>
          </div>
          <button
              class="reset-range-btn"
              @click="resetTimeRange"
              v-if="!isFullRange"
          >
            重置为完整视频
          </button>
        </div>
      </div>

      <div class="quality-control" v-if="selectedFile">
        <label>GIF质量设置:</label>
        <select v-model="quality">
          <option value="high">高质量 (大文件)</option>
          <option value="medium">中等质量</option>
          <option value="low">低质量 (小文件)</option>
        </select>
      </div>

      <button
          @click="convertToGif"
          :disabled="!selectedFile || isConverting"
          class="convert-btn"
          v-if="selectedFile"
      >
        <span v-if="isConverting">
          转换中...{{ progress }}%
        </span>
        <span v-else>
          {{ isFullRange ? "转换完整视频" : "转换所选���段" }}
        </span>
      </button>
    </div>

    <div class="result-section" v-if="gifUrl">
      <h3>转换结果:</h3>
      <img :src="gifUrl" alt="转换后的GIF" class="gif-preview">
      <div class="action-buttons">
        <button @click="downloadGif" class="download-btn">
          下载GIF
        </button>
        <button @click="resetConverter" class="reset-btn">
          重新转换
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed} from "vue"
import {videoApi} from "@/api/video"
import TimeRangeSlider from "./TimeRangeSlider.vue"

const fileInput = ref<HTMLInputElement | null>(null)
const videoPlayer = ref<HTMLVideoElement | null>(null)
const selectedFile = ref<File | null>(null)
const videoPreview = ref("")
const quality = ref("medium")
const isConverting = ref(false)
const gifUrl = ref("")
const progress = ref(0)
const videoDuration = ref(0)
const timeRange = ref<[number, number]>([0, 0])

const isFullRange = computed(() => {
  return timeRange.value[0] === 0 && timeRange.value[1] === videoDuration.value
})

const formatTime = (seconds: number) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  const ms = Math.floor((seconds % 1) * 10)
  return `${mins}:${secs.toString().padStart(2, "0")}.${ms}`
}

const handleVideoLoad = () => {
  if (videoPlayer.value) {
    videoDuration.value = videoPlayer.value.duration
    timeRange.value = [0, videoDuration.value]
  }
}

const resetTimeRange = () => {
  timeRange.value = [0, videoDuration.value]
}

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    if (file.size > 50 * 1024 * 1024) {
      alert("文件大小不能超过50MB")
      return
    }
    selectedFile.value = file
    videoPreview.value = URL.createObjectURL(file)
  }
}

const handleRangeChange = ([start, end]: [number, number]) => {
  if (videoPlayer.value) {
    const currentTime = videoPlayer.value.currentTime
    if (currentTime < start || currentTime > end) {
      videoPlayer.value.currentTime = start
    }
  }
}

const handleTimeUpdate = () => {
  if (videoPlayer.value) {
    const currentTime = videoPlayer.value.currentTime
    if (currentTime < timeRange.value[0]) {
      videoPlayer.value.currentTime = timeRange.value[0]
    } else if (currentTime > timeRange.value[1]) {
      videoPlayer.value.currentTime = timeRange.value[0]
    }
  }
}

const convertToGif = async () => {
  if (!selectedFile.value) return

  isConverting.value = true
  progress.value = 0

  try {
    const response = await videoApi.convertToGif(
        {
          video: selectedFile.value,
          quality: quality.value as "high" | "medium" | "low",
          start_time: timeRange.value[0],
          end_time: timeRange.value[1]
        },
        (progressEvent) => {
          if (progressEvent.total) {
            progress.value = Math.round((progressEvent.loaded * 100) / progressEvent.total)
          }
        }
    )

    gifUrl.value = URL.createObjectURL(response.data)
  } catch (error) {
    console.error("转换失败:", error)
    alert(error instanceof Error ? error.message : "视频转换失败，请重试")
  } finally {
    isConverting.value = false
  }
}

const downloadGif = () => {
  if (!gifUrl.value) return

  const link = document.createElement("a")
  link.href = gifUrl.value
  link.download = `sticker_${Date.now()}.gif`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

const resetConverter = () => {
  selectedFile.value = null
  videoPreview.value = ""
  gifUrl.value = ""
  progress.value = 0
  timeRange.value = [0, 0]
  videoDuration.value = 0
  if (fileInput.value) {
    fileInput.value.value = ""
  }
}
</script>

<style lang="scss" scoped>
.video-converter {
  .upload-section {
    margin-bottom: 30px;

    .upload-box {
      border: 2px dashed #ccc;
      padding: 40px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #4CAF50;
      }

      .upload-hint {
        .upload-icon {
          font-size: 48px;
          margin-bottom: 10px;
        }

        p {
          color: #666;
        }
      }
    }

    .quality-control {
      margin: 20px 0;

      select {
        margin-left: 10px;
        padding: 8px;
        border-radius: 4px;
      }
    }

    .preview {
      margin: 20px 0;

      video {
        max-width: 100%;
        border-radius: 8px;
      }
    }
  }

  .convert-btn, .download-btn, .reset-btn {
    padding: 10px 20px;
    font-size: 16px;
    cursor: pointer;
    border: none;
    border-radius: 4px;
    margin: 0 10px;
    transition: all 0.3s;

    &:disabled {
      background-color: #cccccc;
      cursor: not-allowed;
    }
  }

  .convert-btn {
    background-color: #4CAF50;
    color: white;

    &:hover:not(:disabled) {
      background-color: #45a049;
    }
  }

  .download-btn {
    background-color: #2196F3;
    color: white;

    &:hover {
      background-color: #1976D2;
    }
  }

  .reset-btn {
    background-color: #f44336;
    color: white;

    &:hover {
      background-color: #d32f2f;
    }
  }

  .result-section {
    margin-top: 30px;

    .gif-preview {
      max-width: 100%;
      margin: 20px 0;
      border-radius: 8px;
    }

    .action-buttons {
      display: flex;
      justify-content: center;
      gap: 10px;
    }
  }

  .video-preview {
    margin: 20px 0;

    video {
      max-width: 100%;
      border-radius: 8px;
      margin-bottom: 20px;
    }

    .time-range-selector {
      padding: 20px;
      background: #f5f5f5;
      border-radius: 8px;

      .time-slider {
        width: 100%;

        .slider-container {
          padding: 10px 20px;
        }

        .time-labels {
          display: flex;
          justify-content: space-between;
          margin-top: 10px;
          color: #666;
          font-size: 14px;
        }
      }

      .reset-range-btn {
        margin-top: 10px;
        padding: 5px 10px;
        background: #666;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;

        &:hover {
          background: #555;
        }
      }
    }
  }
}
</style> 